package br.com.neb.caronamanager.model.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import br.com.neb.caronamanager.model.Carona;

public class DB {

	private SQLiteDatabase db;
	private DBInitializer dbInit;
	public DB(Context context)
	{
		dbInit = new DBInitializer(context);
		db = dbInit.getWritableDatabase();
	}
	
	public void insert(Carona obj)
	{
		ContentValues values = new ContentValues();
		
		values.put(DBInitializer.TABLE_CARONA_COLUMNS[1], obj.getDate());
		values.put(DBInitializer.TABLE_CARONA_COLUMNS[2], obj.getDriver());
		values.put(DBInitializer.TABLE_CARONA_COLUMNS[3], obj.getRoundTrip());
		
		db.insert(DBInitializer.TABLE_CARONA, null, values);
	}
	
	public void update(Carona obj)
	{
		ContentValues values = new ContentValues();
		values.put(DBInitializer.TABLE_CARONA_COLUMNS[1], obj.getDate());
		values.put(DBInitializer.TABLE_CARONA_COLUMNS[2], obj.getDriver());
		values.put(DBInitializer.TABLE_CARONA_COLUMNS[3], obj.getRoundTrip());
		
		db.update(DBInitializer.TABLE_CARONA,values,"_id = ?",new String[]{String.valueOf(obj.getId())});
	}
	
	public void delete(Carona obj)
	{
		try{
			db.delete(DBInitializer.TABLE_CARONA,"_id = ?",new String[]{String.valueOf(obj.getId())});
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public List<Carona> search()
	{
		List<Carona> result = new ArrayList<Carona>();
		Cursor cursor = db.query(DBInitializer.TABLE_CARONA, DBInitializer.TABLE_CARONA_COLUMNS, null, null, null, null, null);
		
		if(cursor.getCount() > 0 )
		{
			cursor.moveToFirst();
			do {
				Carona carona = new Carona();
				carona.setId(cursor.getInt(0));
				carona.setDate(cursor.getInt(1));
				carona.setDriver(cursor.getString(2));
				carona.setRoundTrip(cursor.getInt(3));
				result.add(carona);
			} while (cursor.moveToNext());
		}
		return result;
	}
	
	private void open(){
		db = dbInit.getWritableDatabase();
	}
	
	private void close(){
		dbInit.close();
	}
	
	
}
